package com.guangzhi.weijianzhi.company.center;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.guangzhi.weijianzhi.R;
import com.guangzhi.weijianzhi.activity.AlterPassWordActivity;
import com.guangzhi.weijianzhi.activity.BaseActivity;
import com.guangzhi.weijianzhi.activity.LoginActivity;
import com.guangzhi.weijianzhi.context.WeiJianZhiEntity;
import com.guangzhi.weijianzhi.http.HttpRequestUtils;
import com.guangzhi.weijianzhi.utils.Misc;
import com.loopj.android.http.AsyncHttpResponseHandler;

/**
 * 设置界面
 * @author Administrator
 *
 */
public class ComSettingActivity extends BaseActivity implements OnClickListener, OnCheckedChangeListener {
	private String path = Environment.getExternalStorageDirectory().getPath()
			+ "/weijianzhi/";
	private long folderSize;
	private TextView mClearText;
	
	private String busines_qq="";
	private String customer_qq="";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tz_com_setting_layout);
		initData();
		initView();
	}
	
	
	private void initView() {
		// TODO Auto-generated method stub
		
		initTitle();
		titleTextV.setText("设置");
		
		findViewById(R.id.pass_setting).setOnClickListener(this);
		findViewById(R.id.shangwu_setting).setOnClickListener(this);
		findViewById(R.id.suggest_setting).setOnClickListener(this);
		findViewById(R.id.service_setting).setOnClickListener(this);
		findViewById(R.id.notice_setting).setOnClickListener(this);
		findViewById(R.id.clera_setting).setOnClickListener(this);
		findViewById(R.id.wjz_setting).setOnClickListener(this);
		findViewById(R.id.explain).setOnClickListener(this);
		findViewById(R.id.exit_app).setOnClickListener(this);
		goBack.setOnClickListener(this);
		
		mClearText = (TextView) findViewById(R.id.clear_text);
		mClearText.setText(getFormatSize(folderSize));
	}


	private void initData() {
		// TODO Auto-generated method stub
		File dataFile = new File(path);

		try {
			folderSize = getFolderSize(dataFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		HttpRequestUtils.doHttpSettingItem( new AsyncHttpResponseHandler() {
			
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				// TODO Auto-generated method stub
				try {
					JSONObject jsonO = new JSONObject(new String(arg2));
					if(jsonO.optBoolean("status")){
						JSONArray jsonA = jsonO.optJSONArray("data");
						
						JSONObject optJSONObject = jsonA.optJSONObject(0);
						busines_qq = optJSONObject.optString("busines_qq");
						customer_qq = optJSONObject.optString("customer_qq");
					}
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				// TODO Auto-generated method stub
				
			}
		});
	}


	/**
	 * 获取文件夹大小
	 * 
	 * @param file
	 *            File实例
	 * @return long
	 */
	public static long getFolderSize(java.io.File file) {

		long size = 0;
		try {
			java.io.File[] fileList = file.listFiles();
			for (int i = 0; i < fileList.length; i++) {
				if (fileList[i].isDirectory()) {
					size = size + getFolderSize(fileList[i]);

				} else {
					size = size + fileList[i].length();

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return size;
	}
	
	/**
	 * 删除指定目录下文件及目录
	 * 
	 * @param deleteThisPath
	 * @param filepath
	 * @return
	 */
	public void deleteFolderFile(String filePath, boolean deleteThisPath)
			throws IOException {
		if (!TextUtils.isEmpty(filePath)) {
			File file = new File(filePath);

			if (file.isDirectory()) {// 处理目录
				File files[] = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					deleteFolderFile(files[i].getAbsolutePath(), true);
				}
			}
			if (deleteThisPath) {
				if (!file.isDirectory()) {// 如果是文件，删除
					file.delete();
				} else {// 目录
					if (file.listFiles().length == 0) {// 目录下没有文件或者目录，删除
						file.delete();
					}
				}
			}
		}
	}
	
	
	
	
	
	/**
	 * 格式化单位
	 * 
	 * @param size
	 * @return
	 */
	public static String getFormatSize(double size) {
		double kiloByte = size / 1024;
		if (kiloByte < 1) {
			return size + "Byte(s)";
		}

		double megaByte = kiloByte / 1024;
		if (megaByte < 1) {
			BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
			return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
					.toPlainString() + "KB";
		}

		double gigaByte = megaByte / 1024;
		if (gigaByte < 1) {
			BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
			return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
					.toPlainString() + "MB";
		}

		double teraBytes = gigaByte / 1024;
		if (teraBytes < 1) {
			BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
			return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
					.toPlainString() + "GB";
		}
		BigDecimal result4 = new BigDecimal(teraBytes);
		return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
				+ "TB";
	}


	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent;
		switch (v.getId()) {
		case R.id.pass_setting://密码设置
			intent = new Intent(this, AlterPassWordActivity.class);
			startActivity(intent);
			break;
		case R.id.shangwu_setting://商务合作
			if(Misc.notNull(busines_qq)){
				try {
					String url = "mqqwpa://im/chat?chat_type=wpa&uin="+busines_qq+"&version=1"; // uin为目标QQ号！
					startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
				} catch (Exception e) {
					Toast.makeText(this, "未找到QQ程序，请提前安装~",
							Toast.LENGTH_SHORT).show();
				}
			}
			
			break;
		case R.id.suggest_setting://意见反馈
			intent = new Intent(this,EdittextActivity.class);
			intent.putExtra("name", "4");
			startActivity(intent);
			
			break;
		case R.id.service_setting://客服投诉
			if(Misc.notNull(customer_qq)){
				try {
					String url = "mqqwpa://im/chat?chat_type=wpa&uin="+customer_qq+"&version=1"; // uin为目标QQ号！
					startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
				} catch (Exception e) {
					Toast.makeText(this, "未找到QQ程序，请提前安装~",
							Toast.LENGTH_SHORT).show();
				}
			}
			
			break;
		case R.id.notice_setting://通知开关
			
			break;
		case R.id.clera_setting://清除缓存
			clear();
			break;
		case R.id.wjz_setting://关于为兼职
			intent = new Intent(this, WJZActivity.class);
			startActivity(intent);
			break;
		case R.id.explain://使用说明
			
			break;

		case R.id.title_back:
			onBackPressed();
			break;
			
		case R.id.exit_app:
			WeiJianZhiEntity.exitApp();
			Intent intent1 = new Intent(this, LoginActivity.class);
			intent1.putExtra("exit", true);
			startActivity(intent1);
			
			
			finish();
		}
	}


	private void clear() {
		// TODO Auto-generated method stub
		if (folderSize <= 0.01) {
			Toast.makeText(activity, "无需清空", Toast.LENGTH_SHORT).show();
		}else{
			new AlertDialog.Builder(activity)
			.setTitle("提示")
			.setMessage(
					"已占用" + getFormatSize(folderSize) + "内存，您确定要清理缓存吗?")
			.setPositiveButton(android.R.string.ok,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface arg0,
								int arg1) {
							try {
								deleteFolderFile(path, true);
							} catch (IOException e) {
								e.printStackTrace();
							}
							Toast.makeText(activity, "缓存已经清除",
									Toast.LENGTH_SHORT).show();
							mClearText.setText("0.0Byte(s)");
						}
					}).setNegativeButton(android.R.string.cancel, null)
			.create().show();
		}
	}


	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		// TODO Auto-generated method stub
		if(isChecked){
			Misc.alert("通知已打开");
		}else{
			Misc.alert("通知已关闭");
		}
	}
}
